package com.dense.kuiniu.bookborrow.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.IBinder;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.dense.kuiniu.bookborrow.xjSetting.manager.PingBaoManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;


public class BaseDialog extends Dialog {
    public BaseDialog(@NonNull Context context) {
        super(context);
    }

    public BaseDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
    }

    protected BaseDialog(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev)
    {
        PingBaoManager.getInstance().updateClickTime();
        if(ev.getAction() == MotionEvent.ACTION_UP)
        {
            View v = getCurrentFocus();
            if(isShouldHideInput(v,ev))
            {
                hideSoftInput(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }
    private boolean isShouldHideInput(View v, MotionEvent event)
    {
        if(v != null && (v instanceof EditText))
        {
            int[] l = {0,0};
            v.getLocationInWindow(l);
            int left = l[0],top = l[1],bottom = top + v.getHeight(),right = left + v.getWidth();
            if(event.getRawX() > left && event.getRawX() < right && event.getRawY() > bottom && event.getRawY() < top)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        return false;
    }
    private void hideSoftInput(IBinder token)
    {
        if(token != null)
        {
            InputMethodManager im = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token,InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

}
